const wx2my = require('../../wx2my');

// pages/user_order/user_order.js
const app = getApp();
let page = 1;
let totalpage;
Page({
  data: {
    timerId: null,
    tab: [{
      "name": "进行中",
      "index": 0,
      "select": 1,
      "type": 3
    }, {
      "name": "待支付",
      "index": 1,
      "select": 0,
      "type": 0
    }, {
      "name": "已完成",
      "index": 2,
      "select": 0,
      "type": 1
    }],
    type: 3,
    openAgain: 'openAgain',
    stopPull: '',
    macno: '',
    trade_id: '',
    id: '',
    model: '',
    num: 1,
    minusStatus: 'disable',
    minusStatus1: 'normal',
    maxNum: 3,
    imageSrc: '',
    tradeid: '',
    trade_list: [],
    ordertype: 1
  },
  onLoad: function (e) {
    var that = this;

    setTimeout(() => {
      this.permiss()
    }, 200)

    if (e.typeid) {
      let tab_bar = that.data.tab;
      var typeid;
      tab_bar.forEach((item, index) => {
        if (item.type == e.typeid) {
          item.select = 1;
          typeid = item.type;
        } else {
          item.select = 0;
        }
      });
      let status = typeid;
      console.log(status);
      that.setData({
        tab: tab_bar,
        type: status
      });
    }

    this.startTimer();
  },
  onReady: function () {
    let that = this;
    that.get_phone();
  },
  onShow: function () {
    let that = this;
    page = 1;
    that.get_list();
  },

  //联系客服
  tel() {
    let that = this;
    wx2my.showModal({
      title: '温馨提示',
      content: '拨打电话:' + that.data.phoneNum,

      success(res) {
        if (res.confirm) {
          wx2my.makePhoneCall({
            phoneNumber: that.data.phoneNum
          });
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }

    });
  },

  get_phone() {
    let that = this;
    app.wxRequest('customer', {
      'type': 3
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        that.setData({
          phoneNum: res.data.data.tel
        });
      }
    });
  },

  //訂單列表
  get_list() {
    let that = this;
    app.wxRequest('mytrade2', {
      'token': wx2my.getStorageSync('token'),
      'status': that.data.type,
      'page': page
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let list = res.data.data.list;

        if (page == 1) {
          totalpage = res.data.data.totalpage;
        }

        that.setData({
          list: page == 1 ? list : that.data.list.concat(list),
          lock: totalpage <= page ? true : false
        });
        that.updateList();
      }
    });
  },

  showTZM(e) {
    console.log(e);
    // let userId = e.currentTarget.dataset.userId;
    let tradeid = e.currentTarget.dataset.tradeId;
    console.log(tradeid);
    this.setData({
      imageSrc: app.globalData.host+'/index/qrcode?url=h5pro/?tradeid=' + tradeid,
      model: 'ShowTuanZhanMa',
      tradeid: tradeid
    });
  },

  //是否绑定 手机号 
  permiss(e) {
    let that = this;
    app.wxRequest('profile', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        if (res.data.data.account == '' && that.data.auth == 1) {
          //未绑定
          console.log(res.data.data.account);
        }

        if (!that.data.appCode) {

          my.getAuthCode ({
            scopes: ['auth_base'],
            success: function (e) {
              console.log("111getAuthCode11",e);
              let code = e.authCode;
              that.setData({
                appCode: code
              });
            }
          })

        }
      } else {
        wx2my.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 2000
        });
      }
    });
  },

  queding() {
    console.log(this.data.num);
    this.setData({
      model: ''
    });
    let that = this;
    wx2my.scanCode({
      success: res => {
        console.log(res);
        var res = res.result;

        if (res.indexOf('macno') < 0) {
          wx2my.showToast({
            icon: 'none',
            title: '二维码无效'
          });
        } else {
          let macno = app.fm.getUrlParam('macno', res);
          wx2my.setStorageSync('macno', macno);
          that.setData({
            macno: macno
          });
          that.back_toy();
        }
      }
    });
  },

  cancel() {
    this.setData({
      model: ''
    });
  },

  underwayOrder(e) {
    let that = this;
    let tradeid = e.currentTarget.dataset.tradeid;
    console.log(e);
    app.wxRequest('get_trade_desc', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': tradeid
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        that.setData({
          model: 'TradeDesc',
          trade_list: res.data.data
        });
      }
    });
  },

  //事件处理函数

  /*点击减号*/
  bindMinus() {
    var num = this.data.num;

    if (num > 1) {
      num--;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*点击加号*/
  bindPlus() {
    var num = this.data.num;
    console.log(num);

    if (num < this.data.maxNum) {
      num++;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*输入框事件*/
  bindManual(e) {
    var num = e.detail.value;
    console.log(e);

    if (num > this.data.maxNum) {
      num = this.data.maxNum;
    }

    if (num < 1) {
      num = 1;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*顶部tab切换 */
  active(e) {
    if (e.currentTarget.dataset.select == 1) {
      return false;
    }

    var that = this;
    let tab = that.data.tab;
    tab.forEach((item, index) => {
      if (index == e.currentTarget.dataset.index) {
        item.select = 1;
      } else {
        item.select = 0;
      }
    });
    let type = e.currentTarget.dataset.type;
    that.setData({
      tab: tab,
      type: type,
      list: ''
    });
    page = 1;
    that.get_list();
  },

  topay(e) {
    let that = this;
    let trade_id = e.currentTarget.dataset.id;
    wx2my.navigateTo({
      url: '/pages/pay_order/pay_order?trade_id=' + trade_id + '&type=' + 1
    });
  },
  torefunt(e){
    let trade_id = e.currentTarget.dataset.id;
    my.showModal({
      title: '申请退款',
      content: '是否确认申请退款',
      success: function(res) {
        console.log(res);

        wx2my.showToast({
          icon: 'success',
          title: '申请成功！'
        });

      },
      fail: function(err) {
        console.log(err);
      }
    });

  },

  report(e) {
    let that = this;
    let macno = e.currentTarget.dataset.macno;
    wx2my.navigateTo({
      url: '/pages/report/report?macno=' + macno
    });
  },

  //归还
  toReturn(e) {
    let that = this;
    console.log(e);
    let id = e.currentTarget.dataset.id;
    let backnum = e.currentTarget.dataset.backnum;
    let ordertype = e.currentTarget.dataset.ordertype;
    let descid = e.currentTarget.dataset.descid;
    let deevicetype = e.currentTarget.dataset.type;

    if (deevicetype == 1) {
      wx2my.showToast({
        icon: 'none',
        title: '线下无人柜归还请到门店归还'
      });
      return;
    }

    if (backnum == 1) {
      that.setData({
        num: 1,
        id: id,
        ordertype: ordertype,
        descid: descid
      });
      that.queding();
    } else {
      that.setData({
        id: id,
        maxNum: backnum,
        model: 'clickGuiHuan',
        ordertype: ordertype,
        descid: descid
      });
    }
  },

  //归还玩具打开柜门
  back_toy() {
    let that = this;
    wx2my.showLoading({
      title: '开柜中...'
    });
    app.wxRequest('back_toy', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.id,
      'macno': that.data.macno,
      'num': that.data.num,
      'type': that.data.ordertype,
      'descid': that.data.descid
    }, function (res) {
      wx2my.hideLoading();
      console.log(res);

      if (res.data.code == 1) {
        that.setData({
          model: 'open_sus',
          yun_id: res.data.data.yun_id
        });
        that.get_backStatus();
      } else if (res.data.code == -22) {
        that.setData({
          model: 'back_noOrder',
          model: ''
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'no_chest'
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'open_fail',
          yun_id: res.data.data.yun_id
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'have_return'
        });
      } else if (res.data.code == -77) {
        that.setData({
          model: 'back_mistake'
        });
      } else if (res.data.code == -88) {
        that.setData({
          model: 'to_order_store'
        });
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  //归还状态
  get_backStatus() {
    let that = this;
    app.wxRequest('polling_back_toy', {
      'yun_id': that.data.yun_id
    }, function (res) {
      if (res.data.code == 1) {
        app.toast(res.data.msg);
        that.setData({
          model: 'return_sus',
          disinfect_time: res.data.data.disinfect_time
        });
        setTimeout(() => {
          let tab_bar = that.data.tab;
          tab_bar.forEach((item, index) => {
            if (item.type == 1) {
              item.select = 1;
            } else {
              item.select = 0;
            }
          });
          that.setData({
            tab: tab_bar,
            model: '',
            type: 1
          });
          page = 1;
          that.get_list();
        }, 3000);
        wx2my.hideLoading();
      } else if (res.data.code == 0) {
        wx2my.showLoading({
          title: res.data.msg,
          mask: true
        });
        that.data.stopPull = setTimeout(() => {
          that.get_backStatus();
        }, 2000);
      } else if (res.data.code == 2) {
        let trade_id = res.data.data.trade_id;
        that.setData({
          model: 'return_sus',
          disinfect_time: res.data.data.disinfect_time
        });
        setTimeout(() => {
          wx2my.navigateTo({
            url: '/pages/pay_order/pay_order?trade_id=' + trade_id
          });
          that.setData({
            model: ''
          });
        }, 3000);
        wx2my.hideLoading();
      } else if (res.data.code == -11) {
        that.setData({
          model: 'power_fail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -22) {
        that.setData({
          model: 'hand_mistake'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -50) {
        that.setData({
          model: 'hand_fail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -60) {
        that.setData({
          model: 'order_noYour'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -33) {
        that.setData({
          model: 'hand_fail'
        });
        wx2my.hideLoading();
      } else {
        app.toast(res.data.msg);
        wx2my.hideLoading();
      }
    });
  },

  quedingYiCu(e) {
    // 拼团中移除某个用户
    let id = e.currentTarget.dataset.id;
    let tradeid = e.currentTarget.dataset.tradeid;
    let that = this;
    console.log(e);
    wx2my.showModal({
      title: '提示',
      content: '是否确认移除此用户',

      success(res) {
        if (res.confirm) {
          wx2my.showLoading({
            title: '移除中...'
          });
          app.wxRequest('del_trade_tuan', {
            'token': wx2my.getStorageSync('token'),
            'trade_id': tradeid,
            'del_id': id
          }, function (res) {
            wx2my.hideLoading();
            console.log(res);

            if (res.data.code == 1) {
              app.toast(res.data.msg);
              app.wxRequest('get_trade_desc', {
                'token': wx2my.getStorageSync('token'),
                'trade_id': tradeid
              }, function (res) {
                console.log(res);

                if (res.data.code == 1) {
                  that.setData({
                    model: 'TradeDesc',
                    trade_list: res.data.data
                  });
                }
              });
            } else {
              app.toast(res.data.msg);
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }

    });
  },

  //开门失败重新开门
  openAgain() {
    let that = this;
    that.setData({
      model: '',
      openAgain: ''
    });
    that.get_doorOpenstatus();
  },

  get_doorOpenstatus() {
    let that = this;
    wx2my.showLoading({
      title: '开柜中...'
    });
    app.wxRequest('reopen_door', {
      'token': wx2my.getStorageSync('token'),
      'yun_id': that.data.yun_id
    }, function (res) {
      wx2my.hideLoading();
      console.log(res);

      if (res.data.code == 100) {
        that.setData({
          model: 'open_sus'
        });
        that.get_backStatus();
      } else if (res.data.code == -100) {
        that.setData({
          model: 'open_fail'
        });
        app.toast(res.data.msg);
      } else {
        that.setData({
          model: ''
        });
        app.toast(res.data.msg);
      }

      that.setData({
        openAgain: 'openAgain'
      });
    });
  },

  lookOther() {
    this.setData({
      model: ''
    });
    wx2my.navigateTo({
      url: '/pages/home/home'
    });
  },

  del() {
    this.setData({
      model: ''
    });
  },

  // ------租借后3分钟内可以重新开柜
  failOpenagain(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    console.log(id);
    app.wxRequest('reopen_door', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': id
    }, function (res) {
      console.log(res);

      if (res.data.code == 100) {
        that.setData({
          model: 'open_timeout'
        });
      } else if (res.data.code == -100) {
        app.toast(res.data.msg);
        that.setData({
          model: 'door_openFail'
        });
      } else if (res.data.code == -33) {
        app.toast(res.data.msg);
        that.setData({
          model: 'open_timeout'
        });
      } else {
        app.toast(res.data.msg);
        setTimeout(() => {
          wx2my.reLaunch({
            url: '/pages/home/home'
          });
        }, 2000);
      }
    });
  },

  // 启动定时器，每秒检查一次
  startTimer() {
    const timer = setInterval(() => {
      this.updateList();
    }, 1000); // 保存定时器的ID，以便以后可以取消

    this.setData({
      timerId: timer
    });
  },

  // 查询并更新list的showButton状态
  updateList() {
    if (this.data.type == 1 || this.data.type == 0) return;
    const currentTime = new Date().getTime(); // 当前时间的时间戳，单位毫秒

    const threeMinutes = 3 * 60 * 1000; // 3分钟的时间戳，单位毫秒

    if (!this.data.list) {
      this.setData({
        list: []
      });
    }

    let updatedList = this.data.list.map(item => {
      let begintime = item.begintime.replace(/-/g, '/');
      let itemCreateTime = new Date(begintime).getTime(); // 元素的创建时间转换为时间戳
      // 判断创建时间是否在当前时间的前三分钟内

      if (currentTime - itemCreateTime <= threeMinutes) {
        item.showButton = true;
      } else {
        item.showButton = false;
      }

      let timeArr = item.use_time.split(':');
      let hour = parseInt(timeArr[0]);
      let minute = parseInt(timeArr[1]);
      let second = parseInt(timeArr[2]);
      let totalSeconds = hour * 3600 + minute * 60 + second; // 将时间转换为秒数

      totalSeconds++;
      let h = Math.floor(totalSeconds / 3600);
      let m = Math.floor(totalSeconds % 3600 / 60);
      let s = totalSeconds % 60;
      item.use_time = `${h}:${m}:${s}`;
      return item;
    }); // console.log(updatedList);
    // 更新列表状态

    this.setData({
      list: updatedList
    });
  },

  onHide: function () {},
  onUnload: function () {
    let that = this;
    clearInterval(that.data.timerId);
    clearTimeout(that.data.stopPull);
    that.setData({
      model: '',
      stopPull: ''
    });
  },
  onPullDownRefresh: function () {},
  onReachBottom: function () {
    page++;

    if (!this.data.lock) {
      this.get_list();
    }
  },
  onShareAppMessage: function () {}
});